package com.yilu.driver.ui.activity;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.is.common.utils.SPUtils;
import com.is.ui.filter.util.ScreenUtils;
import com.is.ui.widget.CustomPopWindow;
import com.is.ui.widget.IconButton;
import com.is.ui.xrecyclerview.XRecyclerView;
import com.is.ui.xrecyclerview.universaladapter.ViewHolderHelper;
import com.is.ui.xrecyclerview.universaladapter.recyclerview.CommonRecycleViewAdapter;
import com.is.ui.xrecyclerview.universaladapter.recyclerview.OnItemClickListener;
import com.yilu.driver.R;
import com.yilu.driver.base.BaseActivity;
import com.yilu.driver.entity.BatchAllResponse;
import com.yilu.driver.entity.RegisteredTraineeResponse;
import com.yilu.driver.mvp.contract.RegisterTraineeContract;
import com.yilu.driver.mvp.model.RegisterTraineeModel;
import com.yilu.driver.mvp.presenter.RegisterTraineePresenter;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 成绩登记（学员列表）
 *
 * @author Administrator
 * @date 2017/4/15 0015
 */

public class GradeRegistionActivity extends BaseActivity implements RegisterTraineeContract.View, OnItemClickListener {

    @Bind(R.id.ib_back)
    ImageButton ibBack;
    @Bind(R.id.ib_exit)
    ImageButton ibExit;
    @Bind(R.id.ib_search)
    ImageButton ibSearch;
    @Bind(R.id.mFilterContentView)
    XRecyclerView mFilterContentView;
    @Bind(R.id.btn_title)
    IconButton btnTitle;
    @Bind(R.id.btn_select)
    IconButton btnSelect;
    private RegisterTraineeModel model;
    private RegisterTraineePresenter presenter;
    private CommonRecycleViewAdapter<RegisteredTraineeResponse.DataBean> adapter;
    private CustomPopWindow mCustomPopWindow;
    private CustomPopWindow mListPopWindow;
    private CommonRecycleViewAdapter<String> batchAdapter;
    private Integer oprater;//操作人
    private String batch;//批次
    private Integer subject = 1;//科目 默认科目一

    private boolean registion = false;//成绩是否登记
    private CheckBox checkBox;
    private List<RegisteredTraineeResponse.DataBean> traineeList;
    private Drawable arrowUp;//popwindow菜单打开时的图标
    private Drawable arrowDown;//popwindow菜单关闭时的图标
    private String selectTitle;
    private int clickPositon;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_grade_registration;
    }

    @Override
    protected void initViewsAndEvents() {
        oprater = (Integer) SPUtils.get(mContext, "id", 0);
        traineeList = new ArrayList<>();
        adapter = new CommonRecycleViewAdapter<RegisteredTraineeResponse.DataBean>(mContext, R.layout.item_unregistered_trainee) {
            @Override
            public void convert(ViewHolderHelper helper, final RegisteredTraineeResponse.DataBean dataBean) {
                TextView txtTraineeName = helper.getView(R.id.txt_trainee_name);
                TextView txtArchivesNumber = helper.getView(R.id.txt_trainee_archivesNumber);
                TextView txtMobile = helper.getView(R.id.txt_mobile);
                TextView txtCoach = helper.getView(R.id.txt_coach);
                TextView txtStatus = helper.getView(R.id.txt_status);
                checkBox = helper.getView(R.id.chk_select);
                if (registion) {
                    txtStatus.setVisibility(View.GONE);
                    checkBox.setVisibility(View.GONE);
                } else {
                    txtStatus.setVisibility(View.VISIBLE);
                    checkBox.setVisibility(View.VISIBLE);
                    if (dataBean.isChecks()) {
                        checkBox.setChecked(true);
                    } else {
                        checkBox.setChecked(false);
                    }
                    checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                            dataBean.setChecks(b);
                        }
                    });
                }
                txtTraineeName.setText(dataBean.getName());
                txtArchivesNumber.setText("档案号" + dataBean.getArchivesNumber());
                txtMobile.setText("电话" + dataBean.getMobile());
                txtCoach.setText("教练" + dataBean.getCoach());
            }
        };
        mFilterContentView.setLayoutManager(new LinearLayoutManager(this));
        mFilterContentView.setAdapter(adapter);
        adapter.setOnItemClickListener(this);
        //popwindow打开、关闭时的图标
        arrowUp = getResources().getDrawable(R.drawable.common_filter_arrow_up);
        arrowDown = getResources().getDrawable(R.drawable.common_filter_arrow_down);

        arrowUp.setBounds(0, 0, arrowUp.getMinimumWidth(), arrowUp.getMinimumHeight());
        arrowDown.setBounds(0, 0, arrowUp.getMinimumWidth(), arrowUp.getMinimumHeight());
    }

    /**
     * 初始化presenter和model
     */
    @Override
    public void initPresenter() {
        presenter = new RegisterTraineePresenter(mContext);
        model = new RegisterTraineeModel();
        presenter.setVM(this, model);
    }

    /**
     * 数据封装
     * 请求学员列表
     *
     * @param registion true 登记 false 未登记
     * @param operator
     * @param name
     * @param idNumber
     * @param batch
     * @param subject
     */
    public void getRegisterTrainee(boolean registion, Integer operator, String name, String idNumber, String batch, Integer subject) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("operator", operator);
            jsonObject.put("name", name);
            jsonObject.put("idNumber", idNumber);
            jsonObject.put("batch", batch);
            jsonObject.put("subject", subject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (registion) {
            presenter.getRegisterTrainee(jsonObject);
        } else {
            presenter.getUnRegisterTrainee(jsonObject);
        }

    }

    /**
     * 获得批次数据封装成JSONObject
     *
     * @param subject  科目
     * @param operator 操作人id
     */
    private void getBatchAll(Integer subject, Integer operator) {
        JSONObject json = new JSONObject();
        try {
            json.put("subject", subject);
            json.put("operator", operator);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        presenter.getBatchAll(json);
    }

    /**
     * 未登记学员 数据回调
     *
     * @param unRegisteredTrainee
     */
    @Override
    public void returnUnRegisterList(RegisteredTraineeResponse unRegisteredTrainee) {
        traineeList = unRegisteredTrainee.getData();
        for (RegisteredTraineeResponse.DataBean dataBean : unRegisteredTrainee.getData()) {
            dataBean.setChecks(false);
        }
        adapter.replaceAll(unRegisteredTrainee.getData());
        adapter.notifyDataSetChanged();
    }

    /**
     * 已登记学员 数据回调
     *
     * @param unRegisteredTrainee
     */
    @Override
    public void returnRegisterList(RegisteredTraineeResponse unRegisteredTrainee) {
        traineeList = unRegisteredTrainee.getData();
        adapter.replaceAll(unRegisteredTrainee.getData());
        adapter.notifyDataSetChanged();
    }

    /**
     * 批次 数据回调
     *
     * @param batchAllResponse
     */
    @Override
    public void returnBatchAll(BatchAllResponse batchAllResponse) {
        batchAdapter.replaceAll(batchAllResponse.getData());
        batchAdapter.notifyDataSetChanged();
    }

    /**
     * 显示顶部选项菜单
     * 已登记、未登记
     */
    private void showPopMenu() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_menu_registion, null);
        //处理popWindow 显示内容
        handleLogic(contentView);
        //创建并显示popWindow
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .size(ScreenUtils.getScreenWidth(mContext) / 3, ViewGroup.LayoutParams.WRAP_CONTENT)
                .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        btnTitle.setCompoundDrawablesWithIntrinsicBounds(null, null, arrowDown, null);
                    }
                })//关闭popwindowview
                .create()
                .showAsDropDown(btnTitle, 0, 10);
        btnTitle.setCompoundDrawablesWithIntrinsicBounds(null, null, arrowUp, null);//设置title图标
    }

    /**
     * 选项菜单的控制方法
     * 处理弹出显示内容、点击事件等逻辑
     *
     * @param contentView
     */
    private void handleLogic(View contentView) {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.menu1: //已登记请求
                        btnTitle.setText("已登记");
                        registion = true;
                        getRegisterTrainee(true, oprater, "", "", batch, subject);
                        break;
                    case R.id.menu2://未登记请求
                        btnTitle.setText("未登记");
                        registion = false;
                        getRegisterTrainee(false, oprater, "", "", batch, subject);
                        break;
                }
                /**
                 * 关闭popwindowView
                 */
                if (mCustomPopWindow != null) {
                    mCustomPopWindow.dissmiss();
                }
            }
        };
        /**
         * 子item点击事件
         */
        contentView.findViewById(R.id.menu1).setOnClickListener(listener);
        contentView.findViewById(R.id.menu2).setOnClickListener(listener);
    }

    /**
     * activity中控件点击事件
     *
     * @param view
     */
    @OnClick({R.id.btn_title, R.id.btn_select, R.id.btn_register})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_title://菜单
                showPopMenu();
                break;
            case R.id.btn_select://筛选
                showPopList();
                break;
            case R.id.btn_register://登记
                Bundle bundle = new Bundle();
                ArrayList<RegisteredTraineeResponse.DataBean> selectedTrainee = new ArrayList<>();
                for (RegisteredTraineeResponse.DataBean dateBean : traineeList) {
                    if (dateBean.isChecks()) {
                        selectedTrainee.add(dateBean);
                    }
                }
                bundle.putParcelableArrayList("list", selectedTrainee);
                bundle.putInt("subject", subject);
                readyGo(ScoreRegisterActivity.class, bundle); //传递数据到ScoreRegisterActivity
                break;
        }
    }

    /**
     * 弹出筛选列表
     */
    private void showPopList() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_select, null);
        //处理popWindow 显示内容
        handleListView(contentView);
        //创建并显示popWindow
        mListPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .size(ViewGroup.LayoutParams.MATCH_PARENT, ScreenUtils.getScreenHeighth(mContext) / 2)//显示大小
                .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        btnSelect.setCompoundDrawablesWithIntrinsicBounds(null, null, arrowDown, null);//设置筛选图标
                    }
                })
                .create()
                .showAsDropDown(btnSelect, 0, 0);
        btnSelect.setCompoundDrawablesWithIntrinsicBounds(null, null, arrowUp, null);//设置筛选图标
    }

    /**
     * 选项菜单的控制方法
     * 处理弹出显示内容、点击事件等逻辑
     * 筛选列表
     *
     * @param contentView
     */
    private void handleListView(View contentView) {
        getBatchAll(1, oprater);//默认获取科目一的批次
        RecyclerView rcBatch = (RecyclerView) contentView.findViewById(R.id.rc_batch);
        batchAdapter = new CommonRecycleViewAdapter<String>(mContext, R.layout.item_batch) {
            TextView txtBatch;

            @Override
            public void convert(ViewHolderHelper helper, String batch) {
                txtBatch = helper.getView(R.id.txt_batch);
                txtBatch.setText(batch);
                if (clickPositon == helper.getAdapterPosition()) {
                    txtBatch.setBackgroundResource(R.drawable.radiobutton_background_checked);
                    txtBatch.setTextColor(getResources().getColor(R.color.color1));
                }
            }
        };
        rcBatch.setLayoutManager(new GridLayoutManager(mContext, 3));
        rcBatch.setAdapter(batchAdapter);

        batchAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(ViewGroup parent, View view, Object o, int position) {
                clickPositon = position;
                batch = (String) o;
            }

            @Override
            public boolean onItemLongClick(ViewGroup parent, View view, Object o, int position) {
                return false;
            }
        });
        /**
         * 选择科目
         */
        RadioGroup radioGroup = (RadioGroup) contentView.findViewById(R.id.rg_subject);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
                selectTitle = radioButton.getText().toString();
                switch (checkedId) {
                    case R.id.btn_subject_one:
                        subject = 1;
                        getBatchAll(1, oprater);
                        break;
                    case R.id.btn_subject_two:
                        subject = 2;
                        getBatchAll(2, oprater);
                        break;
                    case R.id.btn_subject_three:
                        subject = 3;
                        getBatchAll(3, oprater);
                        break;
                    case R.id.btn_subject_four:
                        subject = 4;
                        getBatchAll(4, oprater);
                        break;
                }
            }
        });
        contentView.findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getRegisterTrainee(registion, oprater, "", "", batch, subject);
                if (mListPopWindow != null) {
                    mListPopWindow.dissmiss();
                }
            }
        });
    }

    @Override
    public void onItemClick(ViewGroup parent, View view, Object o, int position) {

    }

    @Override
    public boolean onItemLongClick(ViewGroup parent, View view, Object o, int position) {
        return false;
    }
}
